package com.yun.algorithmproblem.leetcode;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class Leetcode554 {
    public int leastBricks(List<List<Integer>> wall) {
        int max = 0;
        HashMap<Integer, HashMap<Integer, Integer>> lengthMap = new HashMap<>();
        for (List<Integer> w : wall) {
            int[] sums = new int[2];
            for (int i = 0; i < w.size() - 1; i++) {
                getOverflow(sums, w.get(i));
                HashMap<Integer, Integer> map =
                        lengthMap.computeIfAbsent(sums[1], v -> new HashMap<>());
                int f = map.getOrDefault(sums[0], 0) + 1;
                map.put(sums[0], f);
                if (f > max) {
                    max = f;
                }
            }
        }
        return wall.size() - max;
    }

    private void getOverflow(int[] sums, int a) {
        int sum = sums[0] + a;
        if (sum < 0) {
            sums[0] = sums[0] - Integer.MAX_VALUE + a;
            sums[1]++;
        } else {
            sums[0] = sums[0] + a;
        }
    }

    public static void main(String[] args) {
        List<List<Integer>> lists = new ArrayList<>();
        lists.add(List.of(1, 2, 2, 1));
        lists.add(List.of(3, 1, 2));
        lists.add(List.of(1, 3, 2));
        lists.add(List.of(2, 4));
        lists.add(List.of(3, 1, 2));
        lists.add(List.of(1, 3, 1, 1));
        Leetcode554 obj = new Leetcode554();
        System.out.println(obj.leastBricks(lists));
    }
}
